package com.example.heimashop.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.heimashop.model.CartItem;
import com.example.heimashop.model.Order;
import com.example.heimashop.model.OrderGoods;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单数据访问类
 */
public class OrderDao {
    private DatabaseHelper dbHelper;

    public OrderDao(Context context) {
        this.dbHelper = DatabaseHelper.getInstance(context);
    }

    /**
     * 创建订单
     * @param order 订单对象
     * @param cartItems 购物车商品列表
     * @return 订单ID
     */
    public long createOrder(Order order, List<CartItem> cartItems) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();

        try {
            // 插入订单
            ContentValues orderValues = new ContentValues();
            orderValues.put(DatabaseHelper.COLUMN_ORDER_NO, order.getOrderNo());
            orderValues.put(DatabaseHelper.COLUMN_ORDER_CONSIGNEE, order.getConsignee());
            orderValues.put(DatabaseHelper.COLUMN_ORDER_PHONE, order.getPhone());
            orderValues.put(DatabaseHelper.COLUMN_ORDER_ADDRESS, order.getAddress());
            orderValues.put(DatabaseHelper.COLUMN_TOTAL_PRICE, order.getTotalPrice());
            orderValues.put(DatabaseHelper.COLUMN_STATUS, order.getStatus());
            orderValues.put(DatabaseHelper.COLUMN_CREATE_TIME, order.getCreateTime());

            long orderId = db.insert(DatabaseHelper.TABLE_ORDER, null, orderValues);

            if (orderId != -1) {
                // 插入订单商品
                for (CartItem item : cartItems) {
                    ContentValues goodsValues = new ContentValues();
                    goodsValues.put(DatabaseHelper.COLUMN_ORDER_GOODS_ORDER_ID, orderId);
                    goodsValues.put(DatabaseHelper.COLUMN_ORDER_GOODS_GOODS_ID, item.getGoodsId());
                    goodsValues.put(DatabaseHelper.COLUMN_ORDER_GOODS_NAME, item.getGoodsName());
                    goodsValues.put(DatabaseHelper.COLUMN_ORDER_GOODS_PRICE, item.getGoodsPrice());
                    goodsValues.put(DatabaseHelper.COLUMN_ORDER_GOODS_IMAGE, item.getGoodsImage());
                    goodsValues.put(DatabaseHelper.COLUMN_ORDER_GOODS_COUNT, item.getGoodsCount());

                    db.insert(DatabaseHelper.TABLE_ORDER_GOODS, null, goodsValues);
                }

                db.setTransactionSuccessful();
            }

            return orderId;
        } finally {
            db.endTransaction();
        }
    }

    /**
     * 获取所有订单
     */
    public List<Order> getAllOrders() {
        List<Order> orders = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = db.query(DatabaseHelper.TABLE_ORDER,
                null, null, null, null, null,
                DatabaseHelper.COLUMN_CREATE_TIME + " DESC");

        while (cursor.moveToNext()) {
            Order order = cursorToOrder(cursor);
            // 加载订单商品
            order.setGoodsList(getOrderGoods(order.getId()));
            orders.add(order);
        }
        cursor.close();
        return orders;
    }

    /**
     * 根据状态获取订单
     */
    public List<Order> getOrdersByStatus(String status) {
        List<Order> orders = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = db.query(DatabaseHelper.TABLE_ORDER,
                null,
                DatabaseHelper.COLUMN_STATUS + " = ?",
                new String[]{status},
                null, null,
                DatabaseHelper.COLUMN_CREATE_TIME + " DESC");

        while (cursor.moveToNext()) {
            Order order = cursorToOrder(cursor);
            // 加载订单商品
            order.setGoodsList(getOrderGoods(order.getId()));
            orders.add(order);
        }
        cursor.close();
        return orders;
    }

    /**
     * 根据订单ID获取订单
     */
    public Order getOrderById(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.TABLE_ORDER,
                null,
                DatabaseHelper.COLUMN_ORDER_ID + " = ?",
                new String[]{String.valueOf(id)},
                null, null, null);

        Order order = null;
        if (cursor.moveToFirst()) {
            order = cursorToOrder(cursor);
            order.setGoodsList(getOrderGoods(id));
        }
        cursor.close();
        return order;
    }

    /**
     * 获取订单商品列表
     */
    public List<OrderGoods> getOrderGoods(int orderId) {
        List<OrderGoods> goodsList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = db.query(DatabaseHelper.TABLE_ORDER_GOODS,
                null,
                DatabaseHelper.COLUMN_ORDER_GOODS_ORDER_ID + " = ?",
                new String[]{String.valueOf(orderId)},
                null, null, null);

        while (cursor.moveToNext()) {
            goodsList.add(cursorToOrderGoods(cursor));
        }
        cursor.close();
        return goodsList;
    }

    /**
     * 更新订单状态
     */
    public int updateOrderStatus(int orderId, String status) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_STATUS, status);

        return db.update(DatabaseHelper.TABLE_ORDER,
                values,
                DatabaseHelper.COLUMN_ORDER_ID + " = ?",
                new String[]{String.valueOf(orderId)});
    }

    /**
     * 删除订单
     */
    public int deleteOrder(int orderId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();

        try {
            // 删除订单商品
            db.delete(DatabaseHelper.TABLE_ORDER_GOODS,
                    DatabaseHelper.COLUMN_ORDER_GOODS_ORDER_ID + " = ?",
                    new String[]{String.valueOf(orderId)});

            // 删除订单
            int result = db.delete(DatabaseHelper.TABLE_ORDER,
                    DatabaseHelper.COLUMN_ORDER_ID + " = ?",
                    new String[]{String.valueOf(orderId)});

            db.setTransactionSuccessful();
            return result;
        } finally {
            db.endTransaction();
        }
    }

    /**
     * 生成订单号
     */
    public static String generateOrderNo() {
        return "HM" + System.currentTimeMillis();
    }

    /**
     * 将Cursor转换为Order对象
     */
    private Order cursorToOrder(Cursor cursor) {
        Order order = new Order();
        order.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_ID)));
        order.setOrderNo(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_NO)));
        order.setConsignee(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_CONSIGNEE)));
        order.setPhone(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_PHONE)));
        order.setAddress(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_ADDRESS)));
        order.setTotalPrice(cursor.getDouble(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_TOTAL_PRICE)));
        order.setStatus(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_STATUS)));
        order.setCreateTime(cursor.getLong(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_CREATE_TIME)));
        return order;
    }

    /**
     * 将Cursor转换为OrderGoods对象
     */
    private OrderGoods cursorToOrderGoods(Cursor cursor) {
        OrderGoods goods = new OrderGoods();
        goods.setId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_GOODS_ID)));
        goods.setOrderId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_GOODS_ORDER_ID)));
        goods.setGoodsId(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_GOODS_GOODS_ID)));
        goods.setGoodsName(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_GOODS_NAME)));
        goods.setGoodsPrice(cursor.getDouble(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_GOODS_PRICE)));
        goods.setGoodsImage(cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_GOODS_IMAGE)));
        goods.setGoodsCount(cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_ORDER_GOODS_COUNT)));
        return goods;
    }
}
